import React, { memo, useEffect } from 'react';
import { Form, Select, InputNumber, Input, Switch, Radio } from 'antd';

/**
 * 动态表单
 * TODO: 自定义表单，eg：颜色、列表、上传、富文本
 * @param {*} props 
 * @returns 
 */
const FormRender = props => {
  const { attributes, defaultValue, onSave, uid } = props;

  const normFile = e => {
    if (Array.isArray(e)) {
      //待修改
      return e;
    }
    return e && e.fileList;
  };

  const { Option } = Select;
  const { TextArea } = Input;

  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };

  const onFinish = values => {
    onSave && onSave(values);
  };

  const [form] = Form.useForm();

  useEffect(() => {
    return () => {
      form.resetFields();
    };
  }, [uid, form]);

  const handleChange = () => {
    onFinish(form.getFieldsValue());
  };

  return (
    <Form
      form={form}
      name={`attrForm`}
      {...formItemLayout}
      onFinish={onFinish}
      initialValues={defaultValue}
      onValuesChange={handleChange}
    >
      {(attributes || []).map((item, i) => {
        return (
          <React.Fragment key={i}>
            {item.type === 'Number' && (
              <Form.Item label={item.name} name={item.key}>
                <InputNumber max={item.range && item.range[1]} />
              </Form.Item>
            )}
            {item.type === 'Text' && (
              <Form.Item label={item.name} name={item.key}>
                <Input />
              </Form.Item>
            )}
            {item.type === 'TextArea' && (
              <Form.Item label={item.name} name={item.key}>
                <TextArea rows={4} />
              </Form.Item>
            )}
            {item.type === 'Select' && (
              <Form.Item label={item.name} name={item.key}>
                <Select placeholder="请选择">
                  {item.range.map((v, i) => {
                    return (
                      <Option value={v.key} key={i}>
                        {v.text}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            )}
            {item.type === 'Radio' && (
              <Form.Item label={item.name} name={item.key}>
                <Radio.Group>
                  {item.range.map((v, i) => {
                    return (
                      <Radio value={v.key} key={i}>
                        {v.text}
                      </Radio>
                    );
                  })}
                </Radio.Group>
              </Form.Item>
            )}
            {item.type === 'Switch' && (
              <Form.Item label={item.name} name={item.key} valuePropName="checked">
                <Switch />
              </Form.Item>
            )}
          </React.Fragment>
        );
      })}
    </Form>
  );
};

export default memo(FormRender);
